#!/bin/bash

if [ $# -ne 1 ] && [ $# -ne 2 ] ; then
	echo "logelapse v1.0.0"
	echo "Copyright by Calvin <calvinwilliams@163.com>"
	echo "USAGE : logelapse (log_filename) [ (pid) ]"
	exit 7
fi

LOG_FILENAME=$1
PID=$2

BEGIN_HOUR=0
BEGIN_MINUTE=0
BEGIN_SECOND=0
BEGIN_MICROSECOND=0

# 2021-10-02 10:52:14.057216 | INFO  | 20353:amqsdk.c:828 | TDHBConnect ok , broker[127.0.0.1:13631] , sock[3]

cat ${LOG_FILENAME} | while read LINE ; do
	echo $LINE | egrep "^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}" >/dev/null
	if [ $? -ne 0 ] ; then
		continue
	fi
	
	END_MICROSECONDSTAMP_STR=`echo $LINE |awk '{print $2}'`
	PID_AND_SOURCE_AND_LINE=`echo $LINE |awk '{print $6}'`
	
	END_HOUR_AND_MINUTE_AND_SECOND_STR=`echo $END_MICROSECONDSTAMP_STR | awk -F. '{print $1}'`
	END_MICROSECOND=`echo $END_MICROSECONDSTAMP_STR | awk -F. '{print $2}'`
	
	END_HOUR=`echo $END_HOUR_AND_MINUTE_AND_SECOND_STR | awk -F: '{print $1}'`
	END_MINUTE=`echo $END_HOUR_AND_MINUTE_AND_SECOND_STR | awk -F: '{print $2}'`
	END_SECOND=`echo $END_HOUR_AND_MINUTE_AND_SECOND_STR | awk -F: '{print $3}'`
	
	END_PID=`echo $PID_AND_SOURCE_AND_LINE | awk -F: '{print $1}'`
	if [ x"$PID" != x"" ] && [ x"$END_PID" != x"$PID" ] ; then
		continue
	fi
	
	if [ $BEGIN_HOUR -eq 0 ] && [ $BEGIN_MINUTE -eq 0 ] && [ $BEGIN_SECOND -eq 0 ] && [ $BEGIN_MICROSECOND -eq 0 ] ; then
		echo $LINE
	else
		DIFF_HOURS=`expr $END_HOUR - $BEGIN_HOUR`
		DIFF_MINUTES=`expr $END_MINUTE - $BEGIN_MINUTE`
		DIFF_SECONDS=`expr $END_SECOND - $BEGIN_SECOND`
		DIFF_MICROSECONDS=`expr $END_MICROSECOND - $BEGIN_MICROSECOND`
		while [ $DIFF_MICROSECONDS -lt 0 ] ; do
			DIFF_MICROSECONDS=`expr $DIFF_MICROSECONDS + 1000000`
			DIFF_SECONDS=`expr $DIFF_SECONDS - 1`
		done
		while [ $DIFF_SECONDS -lt 0 ] ; do
			DIFF_SECONDS=`expr $DIFF_SECONDS + 60`
			DIFF_MINUTES=`expr $DIFF_MINUTES - 1`
		done
		while [ $DIFF_MINUTES -lt 0 ] ; do
			DIFF_MINUTES=`expr $DIFF_MINUTES + 60`
			DIFF_HOURS=`expr $DIFF_HOURS - 1`
		done
		DIFF_SECONDS=`echo "$DIFF_HOURS * 3600 + $DIFF_MINUTES * 60 + $DIFF_SECONDS" | bc`
		
		DIFF_SECONDS_STR=`printf "%08d" $DIFF_SECONDS`
		DIFF_MICROSECONDS_STR=`printf "%06d" $DIFF_MICROSECONDS`
		END_ELAPSE_STR="$DIFF_SECONDS_STR.$DIFF_MICROSECONDS_STR"
		echo $LINE | sed 's/'$END_MICROSECONDSTAMP_STR'/'$END_ELAPSE_STR'/g'
	fi
	
	BEGIN_HOUR=$END_HOUR
	BEGIN_MINUTE=$END_MINUTE
	BEGIN_SECOND=$END_SECOND
	BEGIN_MICROSECOND=$END_MICROSECOND
done

